package com.chijun.mform.create.adapter;

import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.RecyclerView;

import com.chijun.mform.create.field.FieldHandler;
import com.chijun.mform.create.field.IFieldInstallResult;
import com.chijun.mform.create.mode.FormConfig;
import com.chijun.mform.R;
import com.chijun.mform.create.mode.FormField;
import com.chijun.mform.create.mode.FormFieldOption;
import com.chijun.mform.field.view.DialogFieldInstall;
import com.example.ccj.b.c.dialog.SureOrCancelDialog;
import com.example.ccj.u.ImageUtils;

import java.util.Collections;
import java.util.Iterator;
import java.util.List;

/**
 * 添加表单字段展示字段
 */
public class SelectFormFieldShowAdapter extends RecyclerView.Adapter<SelectFormFieldShowAdapter.ViewHolder>{
    private static final String TAG = "SelectFormFieldShowAdapter";
    private List<FormField> formFieldList;
    FormConfig formConfig;

    public SelectFormFieldShowAdapter(FormConfig formConfig){
        this.formConfig = formConfig;
        this.formFieldList = formConfig.getFormFieldList();
    }

    @NonNull
    @Override
    public SelectFormFieldShowAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new SelectFormFieldShowAdapter.ViewHolder(LayoutInflater.
                from(parent.getContext()).
                inflate(R.layout.adapater_select_form_field_show,
                        parent,
                        false));
    }

    @Override
    public void onBindViewHolder(@NonNull SelectFormFieldShowAdapter.ViewHolder holder, int position) {
        FormField formField = formFieldList.get(position);
        holder.text.setText(formField.getName());
        //字段名修改保存
        holder.text.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) { }
            @Override
            public void afterTextChanged(Editable s) {
                formField.setName(s.toString());
            }
        });
        //加载字段提示
        holder.hint.setText(formField.getHint());
        //设置按钮
        holder.rightImg.setOnClickListener(installField(formField,position));
        //删除按钮
        holder.deleretImg.setOnClickListener(deleteItem(position));

        ImageUtils.loadImage(holder.icon.getContext(), FieldHandler.getFieldIcon(formField.getType()),holder.icon);
    }

    @Override
    public int getItemCount() {
        return formFieldList.size();
    }


    public static class ViewHolder extends  RecyclerView.ViewHolder{
        private final ImageView movetImg, rightImg,deleretImg,icon;
        private final TextView hint,re_option;
        private final EditText text;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            movetImg = itemView.findViewById(R.id.move);
            rightImg = itemView.findViewById(R.id.right);
            deleretImg = itemView.findViewById(R.id.delete);
            hint = itemView.findViewById(R.id.hint);
            text = itemView.findViewById(R.id.text);
            re_option = itemView.findViewById(R.id.re_option);
            icon = itemView.findViewById(R.id.icon);
        }
    }

    @Override
    public void onAttachedToRecyclerView(@NonNull RecyclerView recyclerView) {
        super.onAttachedToRecyclerView(recyclerView);
        //动画
        DefaultItemAnimator defaultItemAnimator = new DefaultItemAnimator();
        defaultItemAnimator.setAddDuration(500);
        defaultItemAnimator.setRemoveDuration(300);
        defaultItemAnimator.setChangeDuration(200);
        defaultItemAnimator.setMoveDuration(200);
        defaultItemAnimator.setSupportsChangeAnimations(true);
        recyclerView.setItemAnimator(defaultItemAnimator);

        //为RecycleView绑定触摸事件
        ItemTouchHelper helper = new ItemTouchHelper(new ItemTouchHelper.Callback() {
            @Override
            public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
                //首先回调的方法 返回int表示是否监听该方向
                int dragFlags = ItemTouchHelper.UP|ItemTouchHelper.DOWN;//拖拽
                int swipeFlags = ItemTouchHelper.LEFT|ItemTouchHelper.RIGHT;//侧滑删除
                return makeMovementFlags(dragFlags,swipeFlags);
            }

            @Override
            public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
                Collections.swap(formFieldList,viewHolder.getAdapterPosition(),target.getAdapterPosition());
                notifyItemMoved(viewHolder.getAdapterPosition(),target.getAdapterPosition());

                //更改控件顺序后，更改顺序编号
                for (int i = 0; i < formFieldList.size(); i++) {
                    formFieldList.get(i).setOrderColumn(i+1);
                }
                return false;
            }

            @Override
            public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
                //侧滑删除事件
                formFieldList.remove(viewHolder.getAdapterPosition());
                notifyItemRemoved(viewHolder.getAdapterPosition());
//                notifyItemRangeRemoved(viewHolder.getAdapterPosition(),getItemCount());

                //删除后，更改顺序编号
                for (int i = 0; i < formFieldList.size(); i++) {
                    formFieldList.get(i).setOrderColumn(i+1);
                }
            }

            @Override
            public boolean isLongPressDragEnabled() {
                //是否可拖拽
                return true;
            }
        });
        helper.attachToRecyclerView(recyclerView);
    }

    //设置字段按钮
    private View.OnClickListener installField(FormField formField,int position){
        return new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DialogFieldInstall install = new DialogFieldInstall(v.getContext(),formField,formConfig, new IFieldInstallResult() {
                    @Override
                    public void onModify(FormField field) {
                        notifyModify(position);
                    }
                });
                install.show();
            }
        };
    }

    /**
     * 删除数据
     * @param position 数据位置
     * @return
     */
    private View.OnClickListener deleteItem(int position){
        return  new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                SureOrCancelDialog sureOrCancelDialog = new SureOrCancelDialog(v.getContext());
                sureOrCancelDialog.setButtonSureText("确定");
                sureOrCancelDialog.setButtonSureClick(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        notifyRemove(position);
                    }
                });
                sureOrCancelDialog.setButtonCancelText("取消");
                sureOrCancelDialog.setButtonCancelClick(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        sureOrCancelDialog.dismiss();
                    }
                });
                sureOrCancelDialog.show();
            }
        };
    }

    private void notifyRemove(int position){
        FormField remove = formFieldList.remove(position);
        notifyItemRemoved(position);
        //重新加载从删除位置往下的所有item，如果删除的是中间，自删除的位置到最后开始是做重新添加操作
        //避免下表越界等错误
        notifyItemRangeRemoved(position,getItemCount());

        //删除该字段的选项
        List<FormFieldOption> remove1 = formConfig.getFormFieldOptionMap().remove(remove.getId());

        if (remove1 != null) {
            for (FormFieldOption formFieldOption : remove1) {
                //选项删除后删除关联的字段
                if (formConfig.getFieldOptionReMap() != null) {
                    formConfig.getFieldOptionReMap().remove(formFieldOption.id);
                }
            }
        }

        //删除其他选项和此字段的关联
        for (FormField formField : formFieldList) {
            if (formConfig.getFormFieldOptionMap().containsKey(formField.getId())) {
                List<FormFieldOption> formFieldOptions = formConfig.getFormFieldOptionMap().get(formField.getId());
                if (formFieldOptions != null) {
                    for (FormFieldOption formFieldOption : formFieldOptions) {
                        List<FormField> fieldList = formConfig.getFieldOptionReMap().remove(formFieldOption.id);
                        if (fieldList != null) {
                            for (FormField next : fieldList) {
                                if (next.getId() == remove.getId()) fieldList.remove(next);
                            }
                        }
                    }
                }
            }
        }


    }

    private void notifyModify(int position){
        this.notifyItemChanged(position);
    }




}
//    InstallFieldDialog installFieldDialog = new InstallFieldDialog(v.getContext(), formFieldBean, new InstallFieldDialog.IInstallFieldtListener() {
//        @Override
//        public void onInstall(FormFieldBean formFieldBean) {
//            notifyModify(position);
//        }}
//    );
//                installFieldDialog.show();